package com.example.goods_manage.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.goods_manage.commons.enums.TokenEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * JWT 工具类
 */
@Slf4j
public class JWTUtil {
    public static final String SECRET_KEY = "123456"; //秘钥
    public static final long TOKEN_EXPIRE_TIME =24 * 15 * 60 * 60 * 1000; //token过期时间 10分钟
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000; //refreshToken过期时间
    private static final String ISSUER = "issuer"; //签发人

    /**
     * 生成签名
     */
    public static String generateToken(Integer id) {
        //Date now = new Date();
        //创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
        long now = System.currentTimeMillis();
        long oneMonthLater = now + (30  * 15 * 60 * 60 * 1000); // 一个月后的毫秒数
        Date expireDate = new Date(oneMonthLater);
        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(new Date())  //签发时间
                .withExpiresAt(expireDate) //过期时间
                .withClaim("id", id) //保存身份标识
                .sign(algorithm);
        return token;
    }

    /**
     * 验证token
     */
    public static TokenEnum verify(String token) {
        try {
            //签名算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();
            verifier.verify(token);
            log.info("token 验证成功");
            return TokenEnum.TOKEN_SUCCESS;
        } catch (TokenExpiredException ex) {
            log.error("token 过期");
            return TokenEnum.TOKEN_EXPIRE;
            //ex.printStackTrace();
        } catch (Exception e) {
            log.error("token 非法");
            return TokenEnum.TOKEN_BAD;
        }
    }

    /**
     * 从token获取uname
     */
    public static Integer getUid(String token) {
        try {
            return JWT.decode(token).getClaim("id").asInt();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return -1;
    }

    public static void main(String[] args) {
        String token = generateToken(1);
        log.info("generateToken token :{}", token);
        TokenEnum verify = verify(token);
        if (!verify.isSuccess()) {
            log.info("token 异常:{}", verify.getName());
        }
        Integer uname = getUid(token);
        log.info("token 正常,允许登录:{}", uname);

    }
}
